import React from 'react';
import { stampFormat } from 'common/tool';
import CustomIcon from './Icon';

export default class extends React.Component {
  constructor(props) {
    super(props);
    this.forceStop = false;
    this.state = {
      duration: undefined,
    };
  }

  // 挂在组建后开始计算计时器
  componentDidMount() {
    const { start, end } = this.props;
    this.calcDuration(start, end);
  }

  // 组件更新时重新计算计时
  componentWillReceiveProps(newProps) {
    console.log(newProps);
    this.calcDuration(newProps.start, newProps.end);
  }

  componentWillUnmount() {
    this.forceStop = true;
  }

  calcDuration = () => {
    const { start, end } = this.props;
    if (this.forceStop) return;
    let duration;
    if (start && end) {
      duration = end - start;
    } else if (start) {
      duration = Date.now() - start;
      window.requestAnimationFrame(this.calcDuration);
    }
    this.setState({duration: stampFormat(duration)});
  }

  render() {
    const { duration } = this.state;
    return <div style={{ marginLeft: '8px', display: 'flex' }}>
      <CustomIcon type="clock" style={{ marginRight: '4px' }} />
      <span>{duration}</span>
    </div>
  }
}
